package cn.xutongxue.book_sales.controller;


import cn.xutongxue.book_sales.base.Result;
import cn.xutongxue.book_sales.entity.Goods;
import cn.xutongxue.book_sales.service.GoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author XuTongXue
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @GetMapping("/getinfo")
    public Result getInfo(@RequestParam("booksCategoryId") Long books_category_id) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper
                .eq("books_category_id",books_category_id);
        List<Goods> list = goodsService.list(wrapper);
        return Result.ok(list);
    }

    @GetMapping("/getall")
    public Result getAll() {
        List<Goods> list = goodsService.list();
        return Result.ok(list);
    }

    @GetMapping("/search")
    public Result search(@RequestParam("searchKey") String key) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper
                .like("books_name",key);
        List<Goods> list = goodsService.list(wrapper);
        if(list.isEmpty()) {
            return Result.fail(1001,"未搜索到任何相关书籍");
        }
        return Result.ok("搜索成功！",list);
    }

    @PostMapping("/add")
    public Result addBook(@RequestBody Goods goods) {
        if (goodsService.save(goods)) {
            return Result.ok(null);
        }
        return Result.fail(1004,"添加失败");
    }

    @PostMapping("/delete")
    public Result deleteBook(@RequestBody Goods goods) {

        if (goodsService.removeById(goods.getBooksId()))
            return Result.ok(null);
        return Result.fail(1005,"删除失败");
    }

    @PostMapping("/update")
    public Result updateBook(@RequestBody Goods goods) {

        if(goodsService.updateById(goods))
            return Result.ok(null);
        return Result.fail(1006,"修改失败");
    }
}
